package com.realbrand.net.realbrandpay.ui.activity.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.IGetCode;
import com.realbrand.net.realbrandpay.inter.IRegist;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.untils.Static;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/6/20.
 */

public class RegistActivity extends BaseActivity {

    @BindView(R.id.regist_et_phone)
    EditText registEtPhone;
    @BindView(R.id.regist_iv_clean)
    ImageView registIvClean;
    @BindView(R.id.regist_tv_phoneMistake)
    TextView registTvPhoneMistake;
    @BindView(R.id.regist_et_phoneCode)
    EditText registEtPhoneCode;
    @BindView(R.id.regist_bt_sendPhoneCode)
    Button registBtSendPhoneCode;
    @BindView(R.id.regist_tv_phoneCodeMistake)
    TextView registTvPhoneCodeMistake;
    @BindView(R.id.regist_bt_regist)
    Button registBtRegist;
    @BindView(R.id.regist_toolbar)
    Toolbar registToolbar;

//    private JSONObject object = null;

    //用户输入的手机号码
    private String userPhone;

    private TimeCount time;

    @Override
    protected int getLayoutId() {
        return R.layout.regist_activity;
    }

    @Override
    protected void setOnClick() {
        //点击清除手机号
        registIvClean.setOnClickListener(this);
        //点击发送验证码
        registBtSendPhoneCode.setOnClickListener(this);
        //点击注册
        registBtRegist.setOnClickListener(this);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        registToolbar.setTitle("");
        registToolbar.setNavigationIcon(R.mipmap.ic_back_b);
        setSupportActionBar(registToolbar);
        registToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegistActivity.this, LoginActivity.class));
                finish();
            }
        });
        registTvPhoneMistake.setVisibility(View.INVISIBLE);
        registTvPhoneCodeMistake.setVisibility(View.INVISIBLE);
        time = new TimeCount(120000, 1000);
        setOnClick();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.regist_iv_clean:
                //清除手机号码
                registEtPhone.setText("");
                registTvPhoneMistake.setVisibility(View.INVISIBLE);
                break;
            case R.id.regist_bt_sendPhoneCode:
                //先获取用户输入的手机号是否为null，再判断手机号码格式是否正确

                userPhone = registEtPhone.getText().toString();
                if (TextUtils.isEmpty(userPhone)) {
                    Static.toast(this, "请输入手机号码");
                } else {
                    if (Static.isMobileNO(userPhone)) {
                        registTvPhoneMistake.setVisibility(View.INVISIBLE);
                        //做请求
                        registBtSendPhoneCode.setClickable(false);
                        request(userPhone);
                    } else {
                        Static.toast(this, "请输入正确的手机号");
                        registTvPhoneMistake.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case R.id.regist_bt_regist:
                userPhone = registEtPhone.getText().toString();
                String phoneCode = registEtPhoneCode.getText().toString();
                if (TextUtils.isEmpty(userPhone)) {
                    Static.toast(this, "请输入手机号");
                } else {
                    if (Static.isMobileNO(userPhone)) {
                        if (TextUtils.isEmpty(phoneCode)) {
                            Static.toast(this, "请输入验证码");
                        } else {
                            regist(phoneCode);
                        }
                    } else {
                        Static.toast(this, "请输入正确的手机号");
                    }
                }

                break;
        }

    }

    private void regist(String phoneCode) {
        JSONObject registJson = new JSONObject();
        try {
            registJson.put("SOURCE", "RegistActivity");
            registJson.put("METHOD", "VerifyAuthCode");
            registJson.put("CREDENTIALS", "0");
            registJson.put("TERMINAL", "1");
            registJson.put("INDEX", Static.getDay());
            registJson.put("UserMobile", userPhone);
            registJson.put("Verification", phoneCode);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(HTTPAPI.JSON, registJson.toString());
        Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
        IRegist iRegist = retrofit.create(IRegist.class);
        final Call<ResponseBody> regist = iRegist.regist(body);
        regist.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                //请求成功的结果
                if (response == null) {
                    Static.toast(RegistActivity.this, "网络繁忙");
                } else {
                    try {
                        String registRualt = response.body().string();
                        Log.d("zhu", "注册请求成功的结果:" + registRualt);
                        try {
                            JSONObject registJson = new JSONObject(registRualt);
                            JSONArray data = registJson.getJSONArray("DATA");
                            JSONObject registObject = data.getJSONObject(0);
                            String result = registObject.getString("result");
                            if ("true".equals(result)) {
                                //表示验证码正确
                                Intent intent = new Intent(RegistActivity.this, DatumActivity.class);
                                intent.putExtra("UserPhone", userPhone);
                                startActivity(intent);
                                finish();
                            } else if ("验证码错误".equals(result)) {
                                //表示该号码已经注册过了
                                Static.toast(RegistActivity.this, "验证码错误");
                            } else if ("验证码已过时".equals(result)) {
                                Static.toast(RegistActivity.this, "验证码错误");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("zhu", t.toString());
            }
        });

    }

    private void request(String phone) {
        JSONObject object = new JSONObject();

        try {
            object.put("METHOD", "AccountProving");
            object.put("SOURCE", "RegistActivity");
            object.put("CREDENTIALS", "0");
            object.put("TERMINAL", "1");
            object.put("INDEX", Static.getDay());
            object.put("UserMobile", phone);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(HTTPAPI.JSON, object.toString());
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HTTPAPI.BASE_URL)
                .build();
        IGetCode phoneCode = retrofit.create(IGetCode.class);
        Call<ResponseBody> call = phoneCode.getCode(body);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Log.d("zhu", "请求成功，结果是：" + string);
                    JSONObject json = new JSONObject(string);
                    JSONArray data = json.getJSONArray("DATA");
                    JSONObject jsonObject = data.getJSONObject(0);
                    String result = jsonObject.getString("result");
                    if ("false".equals(result)) {
                        time.start();
                    } else if ("true".equals(result)) {
                        Static.toast(RegistActivity.this, "手机号已注册");
                        registBtSendPhoneCode.setClickable(true);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    registBtSendPhoneCode.setClickable(true);
                } catch (JSONException e) {
                    e.printStackTrace();
                    registBtSendPhoneCode.setClickable(true);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("zhu", "请求失败，原因是：" + t.toString());
                registBtSendPhoneCode.setClickable(true);
            }
        });
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            registBtSendPhoneCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
            registBtSendPhoneCode.setClickable(false);
            registBtSendPhoneCode.setText(millisUntilFinished / 1000 + "s后可重发");
        }

        @Override
        public void onFinish() {
            registBtSendPhoneCode.setText("重新获取验证码");
            registBtSendPhoneCode.setClickable(true);
            registBtSendPhoneCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
        }
    }

}
